//
//  OperationBillManagerListVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/11/9.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "OperationBillManagerListVC.h"
#import "OperationBillListHeadView.h"
#import "OperationBillMainModel.h"
#import "OperationBillListCell.h"
#import "OperationBillDetailVC.h"
#import "LJInPutTool.h"
#import "BoHuiReasonAlertView.h"
#import "OperationBillDiaoDuVC.h"
#import "ErWeiMaView.h"
#import "OperationBillGuiJiVC.h"

@interface OperationBillManagerListVC () <UITableViewDelegate,UITableViewDataSource> {
    int type;
    int page;
    int bohui_os_id;
    int shouhuo_os_id;
}

@property (nonatomic, strong) OperationBillListHeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <OperationBillMainModel *>*array;
@property (nonatomic, strong) LJInPutTool *inPutTool;//输入框

@end

@implementation OperationBillManagerListVC

-(LJInPutTool *)inPutTool {
    if (!_inPutTool) {
        _inPutTool = [LJInPutTool new];
        __weak_self;
        _inPutTool.finishBlock = ^(NSString * _Nonnull str) {
            //驳回
            [weakself boHuiBill:str];
        };
    }
    return _inPutTool;
}

- (void)boHuiBill:(NSString *)str {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillBoHui params:@{@"os_id":@(bohui_os_id),@"reject":str} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"驳回成功"];
//            [self refreshData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(OperationBillListHeadView *)headView {
    if (!_headView) {
        _headView = [[OperationBillListHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
        __weak_self;
        _headView.clickBlock = ^(int type) {
            __strong_self;
            strongSelf->page = 1;
            strongSelf->type = type;
            [strongSelf requestForList];
        };
    }
    return _headView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headView.nim_bottom, ScreenW, ScreenH - TabbarHeight - NaviHeight - 40 - self.headView.nim_height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

-(NSMutableArray<OperationBillMainModel *> *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.headView];
    type = 0;
    page = 1;
    [self.view addSubview:self.tableView];
    [self requestForList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
}

- (void)refreshData {
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(self.status) forKey:@"status"];
    [dic setObject:@(type) forKey:@"type"];
    [dic setObject:@(page) forKey:@"page"];
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillList params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.array removeAllObjects];
                self.array = [OperationBillMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.array enumerateObjectsUsingBlock:^(OperationBillMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.billStatus = NO;
                }];
            }else {
                NSArray *array = [OperationBillMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    ((OperationBillMainModel *)obj).billStatus = NO;
                }];
                [self.array addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

- (void)sureBill:(int)os_id {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillAccept params:@{@"os_id":@(os_id)} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已通过"];
//            [self refreshData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)requestForShouHuo:(int)os_id {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillShouHuo params:@{@"os_id":@(os_id)} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已收货"];
//            [self refreshData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OperationBillListCell *cell = [OperationBillListCell OperationBillListCellWithTableView:tableView];
    OperationBillMainModel *model = self.array[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.detailBlock = ^{
        //详情
        OperationBillDetailVC *vc = [OperationBillDetailVC new];
        vc.os_id = model.os_id;
        vc.billStatus = NO;
        vc.hidesBottomBarWhenPushed = YES;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.boHuiBlock = ^{
        //驳回
        __strong_self;
        strongSelf->bohui_os_id = model.os_id;
        strongSelf.inPutTool.placeholder = @"请输入驳回原因";
        strongSelf.inPutTool.sureBtnText = @"确认驳回";
        strongSelf.inPutTool.cancleBtnText = @"取消驳回";
        [strongSelf.inPutTool showInView:MAIN_WINDOW];
    };
    cell.shouLiBlock = ^{
        //受理
        __strong_self;
        strongSelf->bohui_os_id = model.os_id;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定通过操作单吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [strongSelf sureBill:strongSelf->bohui_os_id];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.supplierBoHuiBlock = ^{
        //供应商驳回
        BoHuiReasonAlertView *alert = [BoHuiReasonAlertView new];
        alert.timeStr = model.reject_time;
        alert.reasonStr = model.reject;
        [alert showInView:MAIN_WINDOW];
    };
    cell.codeBlock = ^{
        //查看二维码
        ErWeiMaView *alert = [ErWeiMaView new];
        alert.o_id = model.o_id;
        [alert showInView:MAIN_WINDOW];
    };
    cell.shouHuoBlock = ^{
        //收货
        __strong_self;
        strongSelf->shouhuo_os_id = model.os_id;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定收货吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForShouHuo:strongSelf->shouhuo_os_id];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.driverBoHuiBlock = ^{
        //司机驳回
        OperationBillDetailVC *vc = [OperationBillDetailVC new];
        vc.os_id = model.os_id;
        vc.billStatus = NO;
        vc.hidesBottomBarWhenPushed = YES;
        [self.rt_navigationController pushViewController:vc animated:YES];
//        BoHuiReasonAlertView *alert = [BoHuiReasonAlertView new];
//        alert.timeStr = model.d_reject_time;
//        alert.reasonStr = model.d_reject;
//        [alert showInView:MAIN_WINDOW];
    };
    cell.diaoDuBlock = ^{
        //调度
        OperationBillDiaoDuVC *vc = [OperationBillDiaoDuVC new];
//        vc.os_id = model.os_id;
//        if (model.is_d_reject == 1) {
//            vc.isEdit = YES;
//        }else {
//            vc.isEdit = NO;
//        }
        vc.hidesBottomBarWhenPushed = YES;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    cell.guiJiBlock = ^{
        //查看轨迹
        OperationBillGuiJiVC *vc = [OperationBillGuiJiVC new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.o_id = model.o_id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    OperationBillListCell *cell = [OperationBillListCell OperationBillListCellWithTableView:tableView];
    cell.model = self.array[indexPath.row];
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OperationBillMainModel *model = self.array[indexPath.row];
    OperationBillDetailVC *vc = [OperationBillDetailVC new];
    vc.os_id = model.os_id;
    vc.billStatus = NO;
    vc.hidesBottomBarWhenPushed = YES;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
